<script setup lang="ts">
import { ref, reactive } from "vue";
import { formRules } from "../utils/rule";
import type { FormItemProps } from "../utils/types";
import {
  newsStatusOptions,
  newsCategoryOptions,
  newsTagOptions,
  newsSourceOptions
} from "../utils/types";

interface FormProps {
  formInline: FormItemProps;
}

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    id: null,
    title: "",
    categoryId: 1,
    tags: [],
    coverImage: "",
    summary: "",
    content: "",
    author: "",
    source: "原创",
    status: 0,
    isTop: false,
    isRecommend: false,
    sort: 0,
    publishTime: "",
    remark: ""
  })
});

const ruleFormRef = ref();
const newFormInline = reactive(props.formInline);

function getRef() {
  return ruleFormRef.value;
}

// 处理标签输入
const tagInputVisible = ref(false);
const tagInputValue = ref("");
const tagInputRef = ref();

const handleTagClose = (tag: string) => {
  newFormInline.tags.splice(newFormInline.tags.indexOf(tag), 1);
};

const showTagInput = () => {
  tagInputVisible.value = true;
  nextTick(() => {
    tagInputRef.value!.input!.focus();
  });
};

const handleTagInputConfirm = () => {
  if (tagInputValue.value) {
    if (!newFormInline.tags.includes(tagInputValue.value)) {
      newFormInline.tags.push(tagInputValue.value);
    }
  }
  tagInputVisible.value = false;
  tagInputValue.value = "";
};

// 处理图片上传
const handleImageSuccess = (response: any, file: any) => {
  newFormInline.coverImage = URL.createObjectURL(file.raw);
};

const beforeImageUpload = (file: any) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("上传头像图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="100px"
    class="w-full"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="资讯标题" prop="title">
          <el-input
            v-model="newFormInline.title"
            placeholder="请输入资讯标题"
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="资讯分类" prop="categoryId">
          <el-select
            v-model="newFormInline.categoryId"
            placeholder="请选择资讯分类"
            class="w-full"
          >
            <el-option
              v-for="item in newsCategoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="作者" prop="author">
          <el-input
            v-model="newFormInline.author"
            placeholder="请输入作者"
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="来源" prop="source">
          <el-select
            v-model="newFormInline.source"
            placeholder="请选择来源"
            class="w-full"
            filterable
            allow-create
          >
            <el-option
              v-for="item in newsSourceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="发布状态" prop="status">
          <el-select
            v-model="newFormInline.status"
            placeholder="请选择发布状态"
            class="w-full"
          >
            <el-option
              v-for="item in newsStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="排序值" prop="sort">
          <el-input-number
            v-model="newFormInline.sort"
            :min="0"
            :max="9999"
            placeholder="请输入排序值"
            class="w-full"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="newFormInline.publishTime"
            type="datetime"
            placeholder="选择发布时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            class="w-full"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="置顶">
          <el-switch
            v-model="newFormInline.isTop"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="推荐">
          <el-switch
            v-model="newFormInline.isRecommend"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="标签" prop="tags">
      <div class="tag-container">
        <el-tag
          v-for="tag in newFormInline.tags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleTagClose(tag)"
          class="mr-2 mb-2"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="tagInputVisible"
          ref="tagInputRef"
          v-model="tagInputValue"
          class="tag-input"
          size="small"
          @keyup.enter="handleTagInputConfirm"
          @blur="handleTagInputConfirm"
        />
        <el-button
          v-else
          class="button-new-tag"
          size="small"
          @click="showTagInput"
        >
          + 新标签
        </el-button>
        <div class="mt-2">
          <span class="text-sm text-gray-500">常用标签：</span>
          <el-tag
            v-for="tag in newsTagOptions.slice(0, 8)"
            :key="tag.value"
            size="small"
            type="info"
            class="mr-1 cursor-pointer"
            @click="!newFormInline.tags.includes(tag.value) && newFormInline.tags.push(tag.value)"
          >
            {{ tag.label }}
          </el-tag>
        </div>
      </div>
    </el-form-item>

    <el-form-item label="封面图片" prop="coverImage">
      <el-upload
        class="avatar-uploader"
        action="#"
        :show-file-list="false"
        :on-success="handleImageSuccess"
        :before-upload="beforeImageUpload"
        :auto-upload="false"
      >
        <img v-if="newFormInline.coverImage" :src="newFormInline.coverImage" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <div class="text-sm text-gray-500 mt-2">
        建议尺寸：400x300像素，支持 JPG、PNG 格式，文件大小不超过 2MB
      </div>
    </el-form-item>

    <el-form-item label="资讯摘要" prop="summary">
      <el-input
        v-model="newFormInline.summary"
        type="textarea"
        :rows="3"
        placeholder="请输入资讯摘要，用于列表展示和SEO优化"
        maxlength="500"
        show-word-limit
      />
    </el-form-item>

    <el-form-item label="资讯内容" prop="content">
      <el-input
        v-model="newFormInline.content"
        type="textarea"
        :rows="10"
        placeholder="请输入资讯详细内容"
        class="content-editor"
      />
      <div class="text-sm text-gray-500 mt-2">
        提示：实际项目中这里应该集成富文本编辑器，如 TinyMCE、Quill 等
      </div>
    </el-form-item>

    <el-form-item label="备注" prop="remark">
      <el-input
        v-model="newFormInline.remark"
        type="textarea"
        :rows="2"
        placeholder="请输入备注信息"
        maxlength="500"
        show-word-limit
      />
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.tag-container {
  width: 100%;
  
  .tag-input {
    width: 90px;
    margin-right: 8px;
    margin-bottom: 8px;
  }
  
  .button-new-tag {
    margin-bottom: 8px;
  }
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.content-editor {
  :deep(.el-textarea__inner) {
    min-height: 200px;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  }
}
</style>